package servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import dao.CartItem;
import dao.Goods;

/**
 * Servlet implementation class AddGoodToCart
 */
@WebServlet(
		name="AddGoodToCart",
		urlPatterns= {"/servlet/AddGoodToCart"},
		loadOnStartup = 1
		
		)
public class AddGoodToCart extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddGoodToCart() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		HttpSession session=request.getSession(false);
		RequestDispatcher dispatcher;
		if(session==null) {
			dispatcher=request.getRequestDispatcher("/goodView.jsp");
			dispatcher.forward(request, response);
		}
		Map cart=(Map)session.getAttribute("cart");
		Goods good=(Goods) session.getAttribute("good");
		if(cart==null) {
			cart=new HashMap();
			session.setAttribute("cart", cart);
		}
		CartItem cartItem = (CartItem) cart.get(good.getId());
		if (cartItem != null) 
			cartItem.setQuantity(cartItem.getQuantity() + 1);
		else{		
			CartItem cartItem1=new CartItem();
			cartItem1.setGood(good);;
			cartItem1.setQuantity(1);
			cart.put(good.getId(),cartItem1);
		}			

		
		dispatcher = request.getRequestDispatcher("/viewCart.jsp");
		dispatcher.forward(request, response);
		
	}


	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
